package com.junzhiit.nengji.api.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bainaeco.framework.bean.Email;
import com.bainaeco.framework.util.DateUtil;
import com.bainaeco.framework.util.serializer.Format;
import com.junzhiit.nengji.api.service.EmailService;
import com.junzhiit.nengji.api.service.UserConfigService;
import com.junzhiit.nengji.api.service.UserService;
import com.junzhiit.nengji.api.web.exception.EmailCodeErrorException;
import com.junzhiit.nengji.api.web.exception.EmailCodeTimeoutException;
import com.junzhiit.nengji.api.web.exception.EmailIsExistException;
import com.junzhiit.nengji.api.web.exception.EmailNotRightException;
import com.junzhiit.nengji.api.web.exception.MobilePhoneCodeErrorException;
import com.junzhiit.nengji.api.web.exception.MobilePhoneCodeTimeoutException;
import com.junzhiit.nengji.api.web.exception.MobilePhoneIsExistException;
import com.junzhiit.nengji.api.web.exception.UserNotFoundException;
import com.junzhiit.nengji.api.web.util.Constants;
import com.junzhiit.nengji.api.web.util.FileUtil;
import com.junzhiit.nengji.api.web.util.OrderNumberUtils;
import com.junzhiit.nengji.api.web.util.aliyun.SmsUtil;
import com.junzhiit.nengji.api.web.util.wechat.bean.LoginResponse;
import com.junzhiit.nengji.api.web.vo.AuthVO;
import com.junzhiit.nengji.api.web.vo.EmailCodeVO;
import com.junzhiit.nengji.api.web.vo.ListVO;
import com.junzhiit.nengji.api.web.vo.LoginVO;
import com.junzhiit.nengji.api.web.vo.PhoneCodeVO;
import com.junzhiit.nengji.api.web.vo.ResultVO;
import com.junzhiit.nengji.api.web.vo.UserConfigVO;
import com.junzhiit.nengji.api.web.vo.UserEditVO;
import com.junzhiit.nengji.api.web.vo.UserRelationshipsVO;
import com.junzhiit.nengji.api.web.vo.UserVO;
import com.junzhiit.nengji.bo.UserBO;
import com.junzhiit.nengji.bo.UserRelationshipsBO;
import com.junzhiit.nengji.bo.UserVipBO;
import com.junzhiit.nengji.dao.ShopDAO;
import com.junzhiit.nengji.dao.SystemConfigDAO;
import com.junzhiit.nengji.dao.UserConfigDAO;
import com.junzhiit.nengji.dao.UserDAO;
import com.junzhiit.nengji.dao.UserVipDAO;
import com.junzhiit.nengji.dao.cache.BankCardCheckCountDAO;
import com.junzhiit.nengji.dao.cache.UserCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;
import com.junzhiit.nengji.model.Shop;
import com.junzhiit.nengji.model.SystemConfig;
import com.junzhiit.nengji.model.User;
import com.junzhiit.nengji.model.UserConfig;
import com.junzhiit.nengji.model.enums.IdentityType;
import com.junzhiit.nengji.model.enums.Is;
import com.junzhiit.nengji.model.enums.Language;

@Service
public class UserServiceImpl extends BaseServiceImpl implements UserService {

	@Autowired
	private UserDAO userDAO;

	@Autowired
	private EmailService emailService;

	@Autowired
	private UserCacheDAO userCacheDAO;
	
	@Autowired
	private UserConfigService userConfigService;
	
	@Autowired 
	private UserConfigDAO userConfigDAO;
	
	@Autowired
	private BankCardCheckCountDAO bankCardCheckCountDAO;
	
	@Autowired
	private UserVipDAO userVipDAO;
	
	@Autowired
	private ShopDAO shopDAO;
	
	@Autowired
	private SystemConfigDAO systemConfigDAO;
	
	@Value("${upload.temp}")
	private String uploadPath;

	@Value("${upload.mall.user}")
	private String userPath;

	@Override
	public User checkOpenId(String openId) {
		return userDAO.checkOpenId(openId);
	}

	@Override
	@Transactional
	public ResultVO userAuth(LoginVO loginVO, LoginResponse response) {
		ResultVO result = new ResultVO();
		User user = userDAO.checkOpenId(response.getOpenId());
		Integer isNew = 0;
		String csId = null;
		if (user == null) {
			user = new User();
			user.setNickName(loginVO.getNickName());
			user.setOpenId(response.getOpenId());
			user.setCity(loginVO.getCity());
			user.setAvatarUrl(loginVO.getAvatarUrl());
			user.setSex(loginVO.getGender());
			user.setProvince(loginVO.getProvince());
			user.setCountry(loginVO.getCountry());
			user.setCsId(Constants.INDUSTRY_ROOT);
			if (loginVO.getLanguage().equals("zh_CN")) {
				user.setLanguage(Language.zh_CN.toIntValue());
			} else if (loginVO.getLanguage().equals("zh_TW")) {
				user.setLanguage(Language.zh_TW.toIntValue());
			} else if (loginVO.getLanguage().equals("en")) {
				user.setLanguage(Language.en.toIntValue());
			}
			Long index = userCacheDAO.incr(DIYKey.getMemberCodeStringKey());
			String code = null;
			if(index < 100){
				code = OrderNumberUtils.getUserCode(index.intValue());
			}else{
				code = index.toString();
			}
			user.setCode(code);
			logger.error("code++++++++++++++++"+loginVO.getCode());
			if(StringUtils.isNotBlank(loginVO.getCode())){
				User params =  userDAO.getUserByCode(loginVO.getCode());
				user.setParentId(params.getId());
				user.setFullCode(params.getCode()+"_"+code);
				
				//分享进来赠送积分
				SystemConfig systemConfig = systemConfigDAO.find();
				if(systemConfig != null && systemConfig.getIsOpenShare() == Is.YES.toIntValue()){
					UserConfig userConfig = userConfigDAO.getUserConfig(params.getId());
					userConfig.setLegeIntegral(userConfig.getLegeIntegral()+systemConfig.getOneValue());
					userConfigDAO.update(userConfig);
					if(!params.getParentId().equals(Constants.ROOT_VALUE) ){
						UserConfig secondUser = userConfigDAO.getUserConfig(params.getParentId());
						secondUser.setLegeIntegral(secondUser.getLegeIntegral() + systemConfig.getTwoValue());
						userConfigDAO.update(secondUser);
					}
				}
				
			}else if(StringUtils.isNoneBlank(loginVO.getShopId())){
				User userParams = userDAO.findUserIsMain(loginVO.getShopId());
				if(userParams != null && userParams.getIsMainPromotion() == Is.YES.toIntValue()){
					user.setParentId(userParams.getId());
					user.setFullCode(userParams.getCode()+"_"+code);
				}
			}else{
				user.setParentId(Constants.INDUSTRY_ROOT);
				user.setFullCode(code);
			}
			user.setStatus(Is.YES.toIntValue());
			user.setSubscribeTime(new Date());
			String id = userDAO.insert(user).toString();
			String key = DIYKey.getBankCardCheckCount(id);
		    bankCardCheckCountDAO.addString(key,Constants.CHECK_NUMBER);
		    isNew = 1;
		    csId = Constants.INDUSTRY_ROOT;
		    
		    //单独小程序跳转乐鸽赠送积分
		    logger.error("----------------->"+loginVO.getIsOpenApp());
		    if(loginVO.getIsOpenApp() != null && loginVO.getIsOpenApp() == Is.YES.toIntValue()){
		    	  SystemConfig systemConfig = systemConfigDAO.find();
				    if(systemConfig.getIsOpenShopIntegral() == Is.YES.toIntValue() && systemConfig.getShopIntegralValue() != null){
				    	 Shop shop =	shopDAO.query(loginVO.getShopId());
						    if(shop != null){
						    	shop.setLegeIntegral(shop.getLegeIntegral() + systemConfig.getIsOpenShopIntegral());
						    	shopDAO.update(shop);
						    }
				    }
		    }
		    
		} else if (!user.getAvatarUrl().equals(loginVO.getAvatarUrl())
				|| !user.getNickName().equals(loginVO.getNickName())) {
			user.setAvatarUrl(loginVO.getAvatarUrl());
			user.setNickName(loginVO.getNickName());
			userDAO.update(user);
		}else if(StringUtils.isNoneBlank(user.getCsId())){
			user.setCsId(Constants.INDUSTRY_ROOT);
			boolean is = userDAO.update(user);
			if(is){
				csId = Constants.INDUSTRY_ROOT;
			}
		}
		userConfigService.qrcode(user.getId(),loginVO.getAvatarUrl());
		String key = DIYKey.getCouponsCheckCount(user.getId());
		String newPeople = userCacheDAO.getString(key);

		AuthVO authVO = new AuthVO();
		authVO.setUserId(user.getId());
		authVO.setCode(user.getCode());
		authVO.setIsShop(user.getIsShop());
		authVO.setSessionKey(response.getSessionKey());
		authVO.setIsNew(isNew);
		authVO.setNewPeople(newPeople);
		authVO.setCsId(csId);
		result.setData(authVO);
		return result;
	}

	@Override
	public ResultVO getUserById(String id) {
		ResultVO result = new ResultVO();
		UserBO userBO = userDAO.getUserById(id);

		if (userBO == null) {
			throw new UserNotFoundException("User not found.");
		}
		UserVO userVO = new UserVO();
		BeanUtils.copyProperties(userBO, userVO);
		
		//查询用户身份
		UserVipBO userVipBO = userVipDAO.getVipByUserId(id);
		if(userVipBO != null){
			userVO.setVipIdentity(userVipBO.getIdentity());
			if(userVipBO.getIdentity().equals(IdentityType.CHANNEL_PARTNER.toIntType())){
				userVO.setVipIdentityStr(IdentityType.CHANNEL_PARTNER.toStringValue());
			}else if(userVipBO.getIdentity().equals(IdentityType.COMMON.toIntType())){
				userVO.setVipIdentityStr(IdentityType.COMMON.toStringValue());
			}else if(userVipBO.getIdentity().equals(IdentityType.VIP_USER.toIntType())){
				userVO.setVipIdentityStr(IdentityType.VIP_USER.toStringValue());
			}
		}
		result.setData(userVO);
		return result;
	}

	@Override
	@Transactional
	public ResultVO edit(UserEditVO userEditVO) {
		ResultVO result = new ResultVO();

		User user = userDAO.query(userEditVO.getId());
		if (user == null) {
			throw new UserNotFoundException("User not found.");
		}

		if (StringUtils.isNoneBlank(userEditVO.getHeadImgUrl())) {
			FileUtil.moveFile(uploadPath + userEditVO.getHeadImgUrl(), userPath);
			if (StringUtils.isNoneBlank(user.getAvatarUrl())) {
				FileUtil.removeFile(userPath + user.getAvatarUrl());
			}
		}

		BeanUtils.copyProperties(userEditVO, user);
//		user.setAvatarUrl(userEditVO.getHeadImgUrl());
		try {
			userDAO.update(user);
			result.setData(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public ResultVO sendEmailCode(String userId, String email) {
		ResultVO result = new ResultVO();

		User user = userDAO.query(userId);
		if (user == null) {
			throw new UserNotFoundException("用户没找到");
		}

		User param = userDAO.checkEmail(email);
		if (param != null) {
			String userEmail = user.getEmail();
			if (!StringUtils.isNotBlank(userEmail) || (StringUtils.isNotBlank(userEmail) && !userEmail.equals(email))) {
				throw new EmailIsExistException("邮箱已被使用");
			}
		}

		String randCode = RandomStringUtils.randomNumeric(6);

		// 设置验证码有效时间为10分钟
		Integer timeInt = 10;// 有效时间\分钟
		Date time = DateUtil.addMins(new Date(), timeInt);

		Email mail = new Email();
		mail.setName(Constants.MALL_NAME_KEY);
		mail.setReceivers(new String[] { email });
		mail.setSubject(Constants.EMAIL_SUBJECT_BIND_EMAIL_KEY);
		mail.setBody(Constants.EMAIL_BODY_CODE_TEMPLATE_KEY.replace("{code}", randCode).replace("{time}",
				timeInt.toString()));

		try {
			emailService.sendEmail(mail);

			SmsUtil.RandCode code = new SmsUtil.RandCode();
			code.setCode(randCode);
			code.setTimestamp(time.getTime());

			String key = DIYKey.getEmailCodeKey(email);
			result.setData(userCacheDAO.addHash(key, code));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	@Override
	public ResultVO bindEmail(String userId, String email, String code) {
		ResultVO result = new ResultVO();

		User user = userDAO.query(userId);
		if (user == null) {
			throw new UserNotFoundException("用户没找到");
		}

		User param = userDAO.checkEmail(email);
		if (param != null) {
			String userEmail = user.getEmail();
			if (!StringUtils.isNotBlank(userEmail) || (StringUtils.isNotBlank(userEmail) && !userEmail.equals(email))) {
				throw new EmailIsExistException("邮箱已被使用");
			}
		}

		String key = DIYKey.getEmailCodeKey(email);
		EmailCodeVO emailCodeVO = userCacheDAO.getHash(key, EmailCodeVO.class);
		if (!emailCodeVO.getCode().equals(code)) {
			throw new EmailCodeErrorException("邮箱验证码错误");
		}
		if (emailCodeVO.getTimestamp() < new Date().getTime()) {
			throw new EmailCodeTimeoutException("邮箱验证码已过期");
		}

		user.setEmail(email);
		user.setUpdatedTime(new Date());

		result.setData(userDAO.update(user));
		return result;
	}
	
	@Override
	public ResultVO bindMobilePhone(String userId, String mobilePhone, String code,String name) {
		ResultVO result = new ResultVO();

		User user = userDAO.query(userId);
		if (user == null) {
			throw new UserNotFoundException("用户没找到");
		}

		User param = userDAO.checkMobilePhone(mobilePhone);
		if (param != null) {
			String phone = user.getMobilePhone();
			if (!StringUtils.isNotBlank(phone) || (StringUtils.isNotBlank(phone) && !phone.equals(mobilePhone))) {
				throw new MobilePhoneIsExistException("号码已被使用");
			}
		}

		String key = DIYKey.getMobilePhoneCodeKey(mobilePhone);
		PhoneCodeVO phoneCodeVO = userCacheDAO.getHash(key, PhoneCodeVO.class);
		if (!phoneCodeVO.getCode().equals(code)) {
			throw new MobilePhoneCodeErrorException("手机验证码错误");
		}
		if (phoneCodeVO.getTimestamp() < new Date().getTime()) {
			throw new MobilePhoneCodeTimeoutException("手机验证码已过期");
		}

		user.setMobilePhone(mobilePhone);
		if(StringUtils.isNotBlank(name)){
			user.setName(name);
		}
		user.setUpdatedTime(new Date());

		result.setData(userDAO.update(user));
		return result;
	}

	@Override
	public ResultVO emailCheckSendCode(String userId, String email) {
		ResultVO result = new ResultVO();

		User user = userDAO.query(userId);
		if (user == null) {
			throw new UserNotFoundException("用户没找到");
		}
		if (!user.getEmail().equals(email)) {
			throw new EmailNotRightException("邮箱输入错误");
		}

		String randCode = RandomStringUtils.randomNumeric(6);

		// 设置验证码有效时间为10分钟
		Integer timeInt = 10;// 有效时间\分钟
		Date time = DateUtil.addMins(new Date(), timeInt);

		Email mail = new Email();
		mail.setName(Constants.MALL_NAME_KEY);
		mail.setReceivers(new String[] { email });
		mail.setSubject(Constants.EMAIL_SUBJECT_EMAIL_CKECK_KEY);
		mail.setBody(Constants.EMAIL_BODY_CODE_TEMPLATE_KEY.replace("{code}", randCode).replace("{time}",
				timeInt.toString()));

		try {
			emailService.sendEmail(mail);

			SmsUtil.RandCode code = new SmsUtil.RandCode();
			code.setCode(randCode);
			code.setTimestamp(time.getTime());

			String key = DIYKey.getEmailCodeKey(email);
			result.setData(userCacheDAO.addHash(key, code));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}
	
	@Override
	public ResultVO emailCheck(String userId, String email, String code) {
		ResultVO result = new ResultVO();
		User user = userDAO.query(userId);
		if (user == null) {
			throw new UserNotFoundException("用户没找到");
		}
		if (!user.getEmail().equals(email)) {
			throw new EmailNotRightException("邮箱输入错误");
		}
		String key = DIYKey.getEmailCodeKey(email);
		EmailCodeVO emailCodeVO = userCacheDAO.getHash(key, EmailCodeVO.class);
		if (!emailCodeVO.getCode().equals(code)) {
			throw new EmailCodeErrorException("邮箱验证码错误");
		}
		if (emailCodeVO.getTimestamp() < new Date().getTime()) {
			throw new EmailCodeTimeoutException("邮箱验证码已过期");
		}
		result.setData(true);
		return result;
	}

	@Override
	public ResultVO mobilePhoneCheck(String userId, String code) {
		ResultVO result = new ResultVO();
		User user = userDAO.query(userId);
		if (user == null) {
			throw new UserNotFoundException("用户没找到");
		}
		String key = DIYKey.getMobilePhoneCodeKey(user.getMobilePhone());
		PhoneCodeVO phoneCodeVO = userCacheDAO.getHash(key, PhoneCodeVO.class);
		if (!phoneCodeVO.getCode().equals(code)) {
			throw new MobilePhoneCodeErrorException("手机验证码错误");
		}
		if (phoneCodeVO.getTimestamp() < new Date().getTime()) {
			throw new MobilePhoneCodeTimeoutException("手机验证码已过期");
		}
		result.setData(true);
		return result;
	}

	@Override
	public ResultVO getUserRelationships(String userId,Integer sortStatus,String param,Integer pageNumber,Integer maxPageRow) {
		ResultVO result = new ResultVO();
		User user = userDAO.query(userId);
		if (user == null) {
			throw new UserNotFoundException("用户没找到");
		}
		List<UserRelationshipsBO> list=userDAO.getUserRelationships(userId,sortStatus,param,pageNumber,maxPageRow);
		List<UserRelationshipsVO> userRelationshipsVOList=new ArrayList<UserRelationshipsVO>();
		for (UserRelationshipsBO userRelationshipsBO : list) {
			UserRelationshipsVO userRelationshipsVO=new UserRelationshipsVO();
			BeanUtils.copyProperties(userRelationshipsBO, userRelationshipsVO);
			userRelationshipsVO.setComsumeMoney(userRelationshipsVO.getComsumeMoney()==null?0.00:Format.decimal(userRelationshipsVO.getComsumeMoney()));
			userRelationshipsVO.setOneLevelCount(userRelationshipsVO.getOneLevelCount()==null?0:userRelationshipsVO.getOneLevelCount());
			userRelationshipsVO.setOneComsumeMoney(userRelationshipsVO.getOneComsumeMoney()==null?0.00:Format.decimal(userRelationshipsVO.getOneComsumeMoney()));
//			userRelationshipsVO.setTwoLevelCount(userRelationshipsVO.getTwoLevelCount()==null?0:userRelationshipsVO.getTwoLevelCount());
//			userRelationshipsVO.setTwoComsumeMoney(userRelationshipsVO.getTwoComsumeMoney()==null?0.00:Format.decimal(userRelationshipsVO.getTwoComsumeMoney()));
			userRelationshipsVOList.add(userRelationshipsVO);
		}
		
		int totalCount=userDAO.getUserRelationshipsCount(userId,param);
		
		ListVO listVO = new ListVO();
		listVO.setIndex(pageNumber);
		listVO.setCount(totalCount);
		listVO.setList(userRelationshipsVOList);
		
		result.setData(listVO);
		return result;
	}

	@Override
	public ResultVO takeCash(String userId) {
		ResultVO result = new ResultVO();
		
		User user = userDAO.query(userId);
		if (user == null) {
			throw new UserNotFoundException("用户没找到");
		}
		
		/*UserTakeCashBO userTakeCashBO= userDAO.getUserTakeCash(userId);
		
		userTakeCashBO.setFreeOrdersGoodsCount(userTakeCashBO.getFreeOrdersGoodsCount()==null?0:userTakeCashBO.getFreeOrdersGoodsCount());
		userTakeCashBO.setFreeOrdersGoodsMoney(userTakeCashBO.getFreeOrdersGoodsMoney()==null?0:Format.decimal(userTakeCashBO.getFreeOrdersGoodsMoney()));
		userTakeCashBO.setTotalMoney(userTakeCashBO.getTotalMoney()==null?0:Format.decimal(userTakeCashBO.getTotalMoney()));
		userTakeCashBO.setWaitOrdersGoodsCount(userTakeCashBO.getWaitOrdersGoodsCount()==null?0:userTakeCashBO.getWaitOrdersGoodsCount());
		userTakeCashBO.setWaitTakeCashMoney(userTakeCashBO.getWaitTakeCashMoney()==null?0:Format.decimal(userTakeCashBO.getWaitTakeCashMoney()));*/
		
		UserConfig userConfig = userConfigDAO.getUserConfig(userId);
		UserConfigVO userConfigVO = new UserConfigVO();
		BeanUtils.copyProperties(userConfig, userConfigVO);
		//Double sumMoney = userConfig.getSellMoney()+userConfig.getRebateMoney()+userConfig.getIncomeMoney();
		userConfigVO.setSumMoney(Format.decimal(userConfig.getWithdrawalMoney()));
		result.setData(userConfigVO);
		return result;
	}

	@Override
	public ResultVO updateUserQrcode() {
		ResultVO resultVO = new ResultVO();
		User user = new User();
		List<User> userList = userDAO.findByUser(user);
		for(User params : userList){
			userConfigService.qrcode(params.getId(),params.getAvatarUrl());
		}
		return resultVO;
	}

	@Override
	public ResultVO getUserByCode(String code) {
		ResultVO result = new ResultVO();
		UserBO userBO = userDAO.getUserByUserCode(code);

		if (userBO == null) {
			throw new UserNotFoundException("User not found.");
		}
		UserVO userVO = new UserVO();
		BeanUtils.copyProperties(userBO, userVO);
		
		//查询用户身份
		UserVipBO userVipBO = userVipDAO.getVipByUserId(userBO.getId());
		if(userVipBO != null){
			userVO.setVipIdentity(userVipBO.getIdentity());
			if(userVipBO.getIdentity().equals(IdentityType.CHANNEL_PARTNER.toIntType())){
				userVO.setVipIdentityStr(IdentityType.CHANNEL_PARTNER.toStringValue());
			}else if(userVipBO.getIdentity().equals(IdentityType.COMMON.toIntType())){
				userVO.setVipIdentityStr(IdentityType.COMMON.toStringValue());
			}else if(userVipBO.getIdentity().equals(IdentityType.VIP_USER.toIntType())){
				userVO.setVipIdentityStr(IdentityType.VIP_USER.toStringValue());
			}
		}
		result.setData(userVO);
		return result;
	}

	@Override
	public ResultVO updateUserQrcodeById(String userId) {
		ResultVO result = new ResultVO();
		User user = userDAO.query(userId);
		if (user == null) {
			throw new UserNotFoundException("User not found.");
		}
		userConfigService.qrcode(user.getId(),user.getAvatarUrl());
		return result;
	}
}
